import { defineComponent, ref, watch, nextTick, h } from 'vue'
import * as Icon from "@ant-design/icons-vue"
import { Menu } from 'ant-design-vue/es'
import { useRouter } from 'vue-router'
const { SubMenu, Item } = Menu

export default defineComponent({
  name: 'SMenu',
  props: {
    list: { type: Array, default: () => [] }
  },
  setup(props) {
    const source = ref(props.list)
    const router = useRouter()

    const renderItem = (item) => {
      return item.children && item.children.length > 0 ? renderSubItem(item, item.key) : renderMenuItem(item)
    }

    const renderSubItem = (item, key) => {
      if (item.hideFlag === '1') {
        return null
      } else {
        const hideAll = item.children && item.children.filter((o) => o.hideFlag !== '1')
        if (hideAll.length === 0) {
          return renderMenuItem(item)
        } else {
          const childrenItems =
            item.children &&
            item.children.map((o) => {
              return renderItem(o)
            })
          return (
            <SubMenu icon={item.icon ? () => h(Icon[item.icon]) : null} key={key} title={item.title}>
              {childrenItems}
            </SubMenu>
          )
        }
      }
    }

    const renderMenuItem = (item) => {
      if (item.hideFlag === '1') {
        return null
      } else {
        return (
          <Item key={item.key} icon={item.icon ? () => h(Icon[item.icon]) : null}>
            {item.title}
          </Item>
        )
      }
    }

    const onClick = (item) => {
      router.replace({ name: item.key })
    }

    watch(
      () => props.list,
      (current) => {
        source.value = current
        nextTick(() => { })
      }
    )

    return {
      source,
      renderItem,
      renderSubItem,
      renderMenuItem,
      onClick
    }
  },
  render() {
    const { source, renderItem, onClick } = this
    return (
      <Menu mode="inline" theme="light" onClick={onClick}>
        {source.map((item) => {
          return renderItem(item)
        })}
      </Menu>
    )
  }
})
